package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import com.netflix.discovery.converters.Auto;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: SGS
 * @Date : 2020/11/16 22:08
 * @Version :
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    private final SpecParamService paramService;

    @Autowired
    public SpecGroupServiceImpl(SpecParamService paramService) {
        this.paramService = paramService;
    }

    @Override
    public List<SpecGroupDTO> querySpecList(Long id) {
        //查询规格组信息
        List<SpecGroupDTO> groupDTOS = SpecGroupDTO.convertEntityList(query().eq("category_id", id).list());
        if(CollectionUtils.isEmpty(groupDTOS)){
            throw new LyException(404,"未找到该分类的规格组");
        }
        //查询规格参数,根据分类id
        List<SpecParamDTO> paramDTOS = paramService.queryParams(id, null, null);
        //对规格参数分组,groupId一致的在一组
        Map<Long, List<SpecParamDTO>> map = paramDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        //参数放入group
        for (SpecGroupDTO groupDTO : groupDTOS) {
           groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return groupDTOS;
    }
}
